package com.laxia.util;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.laxia.constant.GlobalConstant;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

/**
 * Created by weishuai on 18/5/14.
 */
@Component
@Slf4j
public class QiniuImgUtil {


    /**
     * 七牛配置(默认国内
     */
    @Value("${qiniu.domain.prefix}")
    private String qiniuDomainPrefix = "http://img.jyqutouba.com/";

    @Value("${qiniu.accessKey}")
    private String accessKey = "_RR6WrA2R7-N0Ur4XKQSjMCCJVJv--0vWPfnDxjB";

    @Value("${qiniu.secretKey}")
    private String secretKey = "WGHZJQNXzqiC6vRWt_vEvq-QC-ykBGF14pqRNry8";

    @Value("${qiniu.bucket}")
    private String bucket = "qutouba";


    /**
     * 地区(默认国内)
     */
    private Configuration cfg;
    private UploadManager uploadManager;

    /**
     * 根据环境变量不通初始化不同上传组件
     */
    @PostConstruct
    public void init() {
        //默认国内
        cfg = new Configuration(Zone.zone0());
        uploadManager = new UploadManager(cfg);
        log.info("=============初始化七牛云配置=========");
    }

    /**
     * 七牛云上传
     *
     * @param data
     * @return 七牛云token
     */
    public String upload(byte[] data, String fileId) {
        return upload("", data, fileId);
    }

    public String upload(InputStream is, String fileId) {
        return upload("", readInputStream(is), fileId);
    }

    /**
     * 七牛云上传
     *
     * @param userName 操作者名字可空
     * @param data
     * @param fileId   文件名唯一名字(不传默认uuid)
     * @return
     */
    public String upload(String userName, byte[] data, String fileId) {

        String result = "";
        DefaultPutRet putRet = null;
        if (StringUtil.isBlank(fileId)) {
            //临时存放通过mes_前缀标识
            fileId = "qtb_" + UUID.randomUUID().toString().replace("_", "");
        }
        try {
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);

            Response response = uploadManager.put(data, fileId, upToken);
            //解析上传成功的结果
            putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            result = putRet.key;
            log.info("上传七牛成功,userName{},fileName:{},result:{}", userName, fileId, JSON.toJSONString(putRet));

        } catch (QiniuException e) {
            log.error("上传七牛失败,userName:{},fileName:{},result:{}", userName, fileId, JSON.toJSONString(putRet), e);
        }
        return result;
    }

    /**
     * 获取客户端上传七牛云token
     *
     * @return
     */
    public String getQinNiuAutoToken() {
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        return upToken;
    }

    /**
     * 获取在七牛的域名
     *
     * @return
     */
    public String getQiniuDomainPrefix() {
        return this.qiniuDomainPrefix;
    }


    /**
     * 从url获取字节数组
     *
     * @param urlPath
     * @return
     */
    public byte[] getImageFromURL(String urlPath) {
        byte[] data = null;
        InputStream is = null;
        HttpURLConnection conn = null;
        try {
            URL url = new URL(urlPath);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(6000);
            is = conn.getInputStream();
            if (conn.getResponseCode() == HttpStatus.OK.value()) {
                data = readInputStream(is);
            } else {
                data = null;
            }
        } catch (Exception e) {
            log.error("url图片转为字节数组异常,param:{}", urlPath, e);
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (Exception e) {
                log.error("url图片转为字节数组finally异常,param:{}", urlPath, e);
            }
            conn.disconnect();
        }
        return data;
    }


    /**
     * 流转为字节数组
     *
     * @param is
     * @return
     */
    public byte[] readInputStream(InputStream is) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length = -1;
        try {
            while ((length = is.read(buffer)) != -1) {
                baos.write(buffer, 0, length);
            }
            baos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
        byte[] data = baos.toByteArray();
        try {
            is.close();
            baos.close();
        } catch (Exception e) {
            log.error("流转为字节数组异常", e);

        }
        return data;
    }

    /**
     * 根据七牛token获取文件完整访问地址
     *
     * @param token
     * @return
     */
    public String getFullUrl(String token) {
        return qiniuDomainPrefix + token;
    }


    public static void main(String[] args) {
        try {
            byte[] uploadBytes = "22122222".getBytes("utf-8");

            QiniuImgUtil util = new QiniuImgUtil();
            util.bucket = "ktrader";
            util.qiniuDomainPrefix = "http://img.ktrader.jyqutouba.com/";
            util.init();
            String token = util.upload(uploadBytes, "1.jpeg");
            System.out.println("七牛返回的token:" + token);

            String url = util.getFullUrl(token);
            System.out.println("七牛完整路径:" + url);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
